package commit;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.app.ActionBar;
import android.support.v7.app.ActionBarActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AbsListView;
import android.widget.Button;
import android.widget.ListView;
import android.widget.Toast;

import com.avos.avoscloud.AVException;
import com.avos.avoscloud.AVFile;
import com.avos.avoscloud.AVObject;
import com.avos.avoscloud.AVQuery;
import com.avos.avoscloud.AVUser;
import com.avos.avoscloud.DeleteCallback;
import com.avos.avoscloud.FindCallback;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;

import co.yeye.test.Constance;
import co.yeye.test.ImageBrowser;
import co.yeye.test.MainActivity;
import co.yeye.test.R;
import listadapter.DiscoveryItemAdapter;
import models.DiscoveryObject;

/**
 * Created by yeye on 15/3/1.
 */
public class UserDiscovery extends ActionBarActivity implements DiscoveryItemAdapter.onClickPicListener,
        DiscoveryItemAdapter.onBottomBtnListener{

    SwipeRefreshLayout layout;
    Button tittle;
    ListView list;
    ImageLoader imageLoader;
    DisplayImageOptions options;
    DiscoveryItemAdapter discoveryItemAdapter;

    boolean isOnListBottom=false;       // 是否在列表底部
    private int page=1;                 // 当前的页数
    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm");   // 日期格式

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // 使用同一个layout
        setContentView(R.layout.user_discovery_layout);
        ActionBar actionBar = this.getSupportActionBar();
        actionBar.setTitle("我的发现");
        actionBar.setBackgroundDrawable(getResources().getDrawable(R.color.blue));

        layout = (SwipeRefreshLayout) findViewById(R.id.swipe_container);
        list = (ListView) findViewById(R.id.listview);
        tittle = (Button) findViewById(R.id.refresh_text);
        tittle.setVisibility(View.GONE);

        imageLoader = MainActivity.getInstance().getImageLoader();
        options = MainActivity.getInstance().getOptionCache();

        discoveryItemAdapter = new DiscoveryItemAdapter(MainActivity.getInstance(),imageLoader,options);
        // 注册按键监听器
        discoveryItemAdapter.setOnClickPicListener(this);
        discoveryItemAdapter.setOnBottomBtnListener(this);

        layout.setColorSchemeResources(android.R.color.holo_blue_light,
                android.R.color.holo_red_light, android.R.color.holo_orange_light,
                android.R.color.holo_green_light);

        list.setAdapter(discoveryItemAdapter);
        list.setOnScrollListener(new AbsListView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(AbsListView absListView, int scrollState) {
                switch (scrollState) {
                    // 当不滚动时
                    case AbsListView.OnScrollListener.SCROLL_STATE_IDLE:
                        // 判断滚动到底部
                        if (absListView.getLastVisiblePosition() == (absListView.getCount() - 1)) {
                            // 避免底部最后一个选项的时候多次刷新
                            if(!isOnListBottom) {
                                if(MainActivity.getInstance().getNetState()== Constance.NETWORK_INVALID) {
                                    Constance.setTittle(getResources().getString(R.string.network_invalid),
                                            getResources().getColor(R.color.red), 0, tittle);
                                    layout.setRefreshing(false);
                                    return;
                                }
                                else
                                    refreshDiscovery(false,false);
                            }
                            isOnListBottom=true;
                        }
                        else
                            isOnListBottom=false;
                        break;
                }
            }

            @Override
            public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {

            }
        });

        layout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                if(MainActivity.getInstance().getNetState()==Constance.NETWORK_INVALID) {
                    Constance.setTittle(getResources().getString(R.string.network_invalid),
                            getResources().getColor(R.color.red), 0, tittle);
                    layout.setRefreshing(false);
                    return;
                }
                Constance.setTittle("正在刷新", Color.parseColor("#6495ed"), 2000, tittle);
                // 获取用户信息
                //final UserObject userObject = MainActivity.getInstance().getUser();
                refreshDiscovery(true,true);
                isOnListBottom=false;
                // text
                //layout.setRefreshing(false);
            }
        });

        refreshDiscovery(true,false);

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.user_discovery, menu);
        return true;
        //return super.onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int id = item.getItemId();
        if (id == R.id.action_return) {
            finish();
            //Toast.makeText(getBaseContext(),"发布",Toast.LENGTH_SHORT).show();
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

    /**
     * 刷新发现列表
     * @param isRefreshOnTop 是否为顶部刷新
     * @param isNotify 是否通知用户
     */
    private void refreshDiscovery(final boolean isRefreshOnTop , final boolean isNotify ){
        // 查询服务器信息
        AVQuery<AVObject> query = new AVQuery<AVObject>("Discovery");
        query.setCachePolicy(AVQuery.CachePolicy.NETWORK_ELSE_CACHE);
        query.setLimit(Constance.SINGLE_REQUEST_ITEM_NUM);
        if(!isRefreshOnTop)
            query.setSkip(Constance.SINGLE_REQUEST_ITEM_NUM * page++);
        else
            page=1;
        query.orderByDescending("createdAt");
        query.include("relation_user");
        // 只查询自己的
        query.whereEqualTo("userCode",MainActivity.getInstance().getUser().getUser_code());
        query.findInBackground(new FindCallback<AVObject>() {
            @Override
            public void done(List<AVObject> avObjects, AVException e) {
                if(e==null){
                    if(avObjects.size()<=0){
                        Constance.setTittle("无更多消息", getResources().getColor(R.color.red), 2000, tittle);
                        layout.setRefreshing(false);
                        return;
                    }
                    // 刷新信息到列表内
                    // 开始构造，保存到ArrayList中
                    ArrayList<DiscoveryObject> objectArrayList = new ArrayList<DiscoveryObject>();
                    for(int i=0;i<avObjects.size();i++){
                        DiscoveryObject discoveryObject = new DiscoveryObject();
                        // 尝试使用关联的AVUser
                        AVUser avUser = avObjects.get(i).getAVUser("relation_user");
                        discoveryObject.setUser_name(avUser.getString("username"));
                        discoveryObject.setUser_img_url(avUser.getAVFile("user_img").getUrl());
                        //discoveryObject.setUser_name(avObjects.get(i).getString("user_name"));
                        //discoveryObject.setUser_img_url(avObjects.get(i).getString("user_img_url"));
                        discoveryObject.setContent(avObjects.get(i).getString("content"));
                        discoveryObject.setDate(simpleDateFormat.format(avObjects.get(i).getCreatedAt()));
                        //discoveryObject.setDate(avObjects.get(i).getCreatedAt().toString());
                        //discoveryObject.setDate("2015.2.18");
                        //int imagesNum = avObjects.get(i).getInt("imagesNum");
                        // 写入图像uri信息
                        ArrayList<String> imgUris = new ArrayList<String>();
                        ArrayList<String> imgUrisOrigin = new ArrayList<String>();
                        for(int j=0;j<9;j++){
                            AVFile imgFile = avObjects.get(i).getAVFile("image"+String.valueOf(j+1));
                            if(imgFile==null)
                                break;
                            imgUris.add(imgFile.getThumbnailUrl(false,300,300));
                            imgUrisOrigin.add(imgFile.getUrl());
                        }
                        discoveryObject.setImg_list(imgUris);
                        discoveryObject.setImg_list_origin(imgUrisOrigin);
                        discoveryObject.setCode(avObjects.get(i).getString("userCode"));
                        discoveryObject.setAvObject(avObjects.get(i));
                        objectArrayList.add(discoveryObject);
                    }
                    // 顶部刷新，则只需要刷新前面的数据即可
                    if(isRefreshOnTop)
                        discoveryItemAdapter.setDiscoveryObjectList(objectArrayList);
                        // 滑动到底部刷新，需要继续加载剩下的项目
                    else
                        discoveryItemAdapter.addDiscoveryObjectList(objectArrayList);
                    //list.setAdapter(discoveryItemAdapter);
                    discoveryItemAdapter.notifyDataSetChanged();
                    //list.notifyAll();
                    layout.setRefreshing(false);
                    if(isNotify)
                        Constance.setTittle("刷新完成", getResources().getColor(R.color.green), 1000, tittle);
                    return;
                }
                else {
                    Toast.makeText(getBaseContext(),e.toString(), Toast.LENGTH_LONG).show();
                    e.printStackTrace();
                    return;
                }
            }
        });
    }


    @Override
    public void bottomBtnClick(final DiscoveryObject obj, int button, int position) {
        // 点赞
        if(button==Constance.DISCOVERY_ITEM_ZHAN){
            Constance.setTittle("功能尚未开放",getResources().getColor(R.color.red),2000,tittle);
        }
        // 删除
        else if(button==Constance.DISCOVERY_ITEM_DELETE){
            AlertDialog alertDialog = new AlertDialog.Builder(UserDiscovery.this)
                    .setTitle("确认删除")
                    .setMessage("删除成功后将无法恢复该条发现记录，请谨慎操作。")
                    .setNegativeButton("取消",new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialogInterface, int i) {

                        }
                    })
                    .setPositiveButton("确定",new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialogInterface, int i) {
                            obj.getAvObject().deleteInBackground(new DeleteCallback() {
                                @Override
                                public void done(AVException e) {
                                    Constance.setTittle("删除成功",getResources().getColor(R.color.green),2000,
                                            tittle);
                                    refreshDiscovery(true,false);
                                }
                            });
                        }
                    })
                    .show();
        }
    }

    @Override
    public void picClick(DiscoveryObject obj, int picNum) {
        ArrayList<String> url = new ArrayList<String>();
        url = obj.getImg_list_origin();
        Intent intent = new Intent(UserDiscovery.this, ImageBrowser.class);
        intent.putStringArrayListExtra("urls",url);
        intent.putExtra("num",picNum-1);
        startActivity(intent);
    }
}
